<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发票号码" prop="invoiceNumber">
        <el-input
          v-model="queryParams.invoiceNumber"
          placeholder="请输入发票号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票方" prop="issuer">
        <el-input
          v-model="queryParams.issuer"
          placeholder="请输入开票方"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票日期">
        <el-date-picker
          v-model="daterangeIssueDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="到期日">
        <el-date-picker
          v-model="daterangeDueDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['operations:invoice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operations:invoice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operations:invoice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['operations:invoice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="invoiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="发票号码" align="center" prop="invoiceNumber" />
      <el-table-column label="发票类型" align="center" prop="invoiceType" />
      <el-table-column label="开票方" align="center" prop="issuer" />
      <el-table-column label="发票金额" align="center" prop="amount" />
      <el-table-column label="税额" align="center" prop="taxAmount" />
      <el-table-column label="开票日期" align="center" prop="issueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期日" align="center" prop="dueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" placeholder="请选择状态" @change="handleStatusChange(scope.row)">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- <el-table-column label="关联支付ID" align="center" prop="paymentId" /> -->
      <el-table-column label="发票图片" align="center" prop="remark">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.remark"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row.remark)"
          >下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['operations:invoice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['operations:invoice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发票管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发票号码" prop="invoiceNumber">
          <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" />
        </el-form-item>
        <el-form-item label="发票类型" prop="invoiceType">
          <el-select v-model="form.invoiceType" placeholder="请选择发票类型">
            <el-option
              v-for="item in invoiceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票方" prop="issuer">
          <el-input v-model="form.issuer" placeholder="请输入开票方" />
        </el-form-item>
        <el-form-item label="发票金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入发票金额" />
        </el-form-item>
        <el-form-item label="税额" prop="taxAmount">
          <el-input v-model="form.taxAmount" placeholder="请输入税额" />
        </el-form-item>
        <el-form-item label="开票日期" prop="issueDate">
          <el-date-picker clearable
            v-model="form.issueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开票日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日" prop="dueDate">
          <el-date-picker clearable
            v-model="form.dueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择到期日">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="关联支付ID" prop="paymentId">
          <el-input v-model="form.paymentId" placeholder="请输入关联支付ID" />
        </el-form-item> -->
        <el-form-item label="发票图片" prop="remark">
          <el-upload
            ref="upload"
            :limit="1"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInvoice, getInvoice, delInvoice, addInvoice, updateInvoice } from "@/api/operations/invoice"
import { getToken } from "@/utils/auth"

export default {
  name: "Invoice",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票管理表格数据
      invoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeIssueDate: [],
      // 备注时间范围
      daterangeDueDate: [],
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/operations/invoice/upload",
        // 上传的文件列表
        fileList: []
      },
      // 发票类型选项
      invoiceTypeOptions: [
        { value: 0, label: '增值税专用发票' },
        { value: 1, label: '增值税普通发票' },
        { value: 2, label: '电子发票（增值税电子普通发票）' },
        { value: 3, label: '通用机打发票' },
        { value: 4, label: '定额发票' }
      ],
      // 状态选项
      statusOptions: [
        { value: 0, label: '未审核' },
        { value: 1, label: '已确认' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceNumber: null,
        invoiceType: null,
        issuer: null,
        issueDate: null,
        dueDate: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        invoiceNumber: [
          { required: true, message: "发票号码不能为空", trigger: "blur" }
        ],
        invoiceType: [
          { required: true, message: "发票类型不能为空", trigger: "change" }
        ],
        issuer: [
          { required: true, message: "开票方不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "发票金额不能为空", trigger: "blur" }
        ],
        taxAmount: [
          { required: true, message: "税额不能为空", trigger: "blur" }
        ],
        issueDate: [
          { required: true, message: "开票日期不能为空", trigger: "blur" }
        ],
        dueDate: [
          { required: true, message: "到期日不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询发票管理列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeIssueDate && '' != this.daterangeIssueDate) {
        this.queryParams.params["beginIssueDate"] = this.daterangeIssueDate[0]
        this.queryParams.params["endIssueDate"] = this.daterangeIssueDate[1]
      }
      if (null != this.daterangeDueDate && '' != this.daterangeDueDate) {
        this.queryParams.params["beginDueDate"] = this.daterangeDueDate[0]
        this.queryParams.params["endDueDate"] = this.daterangeDueDate[1]
      }
      listInvoice(this.queryParams).then(response => {
        this.invoiceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        invoiceNumber: null,
        invoiceType: null,
        issuer: null,
        amount: null,
        taxAmount: null,
        issueDate: null,
        dueDate: null,
        status: null,
        paymentId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeIssueDate = []
      this.daterangeDueDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.upload.fileList = [];
      this.open = true;
      this.title = "添加发票管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInvoice(id).then(response => {
        this.form = response.data;
        if (this.form.remark) {
          this.upload.fileList = [{ name: '发票图片', url: this.form.remark }];
        } else {
          this.upload.fileList = [];
        }
        this.open = true;
        this.title = "修改发票管理";
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      updateInvoice(row).then(response => {
        this.$modal.msgSuccess("状态修改成功");
      }).catch(() => {
        this.$modal.msgError("状态修改失败");
      }).finally(() => {
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInvoice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInvoice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除发票管理编号为"' + ids + '"的数据项？').then(function() {
        return delInvoice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('operations/invoice/export', {
        ...this.queryParams
      }, `invoice_${new Date().getTime()}.xlsx`)
    },
    /** 下载附件 */
    handleDownload(url) {
      window.open(url);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.remark = response.url;
      this.upload.fileList = [{ name: file.name, url: response.url }];
      this.$modal.msgSuccess("上传成功");
    }
  }
}
</script>
